import 'package:flutter/material.dart';

import 'package:flutter/services.dart';
import 'package:r_scan/r_scan.dart';
import 'package:image_picker/image_picker.dart';
import '../services/PermissionAdapter.dart';


class ScanPage extends StatefulWidget {
  ScanPage({Key? key}) : super(key: key);

  @override
  _ScanPageState createState() => _ScanPageState();
}

class _ScanPageState extends State<ScanPage> {
  List<RScanCameraDescription> rScanCameras = [];
  RScanCameraController? _controller;
  bool isFirst = true;
  String scanText = "";
  RScanResult? result;

  Future _scan() async {
    bool hasPermission = await PermissionAdapter.canOpenCamera(openSetting: true);
    if (hasPermission) {
      
    } else {

    }
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  Future<bool> getFlashMode() async {
    bool isOpen = false;
    try {
      isOpen = (await _controller?.getFlashMode())!;
    } catch (_) {}
    return isOpen;
  }

  Widget _buildFlashBtn(BuildContext context, AsyncSnapshot snapshot) {
    // 闪光灯组件
    return snapshot.hasData? Padding(padding:  EdgeInsets.only(bottom:24+MediaQuery.of(context).padding.bottom),
      child: IconButton(
          icon: Icon(snapshot.data ? Icons.flash_on : Icons.flash_off),
          color: Colors.white,
          iconSize: 46,
          onPressed: () {
            if (snapshot.data) {
              _controller?.setFlashMode(false);
            } else {
              _controller?.setFlashMode(true);
            }
            setState(() {});
          }),
    ): Container();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("扫码"),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.camera_roll),
        onPressed: _scan,
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Center(
              child: Text(result == null
                  ? '点击下方按钮开始扫码'
                  : '扫码结果${result.toString().split(',').join('\n')}')),
          // Center(
          //   child: FlatButton(
          //     onPressed: () async {
          //       final result = await Navigator.of(context).push(
          //           MaterialPageRoute(
          //               builder: (BuildContext context) => RScanCameraDialog()));
          //       setState(() {
          //         this.result = result;
          //       });
          //     },
          //     child: Text('RScanCamera开始扫码'),
          //   ),
          // ),
          Center(
            child: FlatButton(
              onPressed: () async {
                if (await PermissionAdapter.canReadStorage(openSetting: true)) {
                  var image = await ImagePicker().getImage(source: ImageSource.gallery);
                  if (image != null) {
                    final result = await RScan.scanImagePath(image.path);
                    setState(() {
                      this.result = result;
                    });
                  }
                }
              },
              child: Text('选择图片扫描'),
            ),
          ),
          Center(
            child: FlatButton(
              onPressed: () async {
                final result = await RScan.scanImageUrl("https://s.cn.bing.net/th?id=OJ.5F0gxqWmxskS0Q&w=75&h=75&pid=MSNJVFeeds");
                setState(() {
                  this.result = result;
                });
              },
              child: Text('网络图片解析'),
            ),
          ),
          Center(
            child: FlatButton(
              onPressed: () async {
                ByteData data = await rootBundle.load('images/2.jpeg');
                final result =
                    await RScan.scanImageMemory(data.buffer.asUint8List());
                setState(() {
                  this.result = result;
                });
              },
              child: Text('内存图片解析'),
            ),
          ),
        ],
      )
    );
  }
}